import threading,time
def increase(var, lock):
    global increase_times
    for i in range(1000000):
        if lock.acquire():#必须要获取锁才能操作
            var[0] += 1
            lock.release()#操作完后，再释放锁
            increase_times += 1


def decrease(var, lock):
    global decrease_times
    for i in range(1000000):
        if lock.acquire():
            var[0] -= 1
            lock.release()
            decrease_times -= 1


if __name__ == '__main__':
    print('main thread is {}'.format(threading.current_thread().name))
    start_time = time.time()
    lock = threading.Lock()####################锁
    """
    线程1在操作变量a的时候就给a上一把锁，
    别的线程看到变量有锁就不会去操作该变量，
    一直到线程1再次获得GIL之后继续操作将锁释放
    别的线程才有机会对该变量进行操作。
    """
    var = [5]
    increase_times = 0#定义变量1
    decrease_times = 0#定义变量2
    t1 = threading.Thread(target=increase, args=(var, lock))#传入锁
    t2 = threading.Thread(target=decrease, args=(var, lock))
    t1.start()
    t2.start()
    t1.join()
    t2.join()
    print(var)
    print('total increase times: {}'.format(str(increase_times)))
    print('total decrease times: {}'.format(str(decrease_times)))
    end_time = time.time()
    print('total time is {}'.format(str(end_time - start_time)))
"""
main thread is MainThread
[5]
total increase times: 1000000
total decrease times: -1000000
total time is 1.3017802238464355
"""